package com.ingenio.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.ingenio.business.PrecioProducto;
import com.ingenio.business.Producto;
import com.ingenio.business.UMProducto;
import com.ingenio.dao.PrecioProductoAdapter;
import com.ingenio.dao.ProductoAdapter;
import com.ingenio.dao.UMProductoAdapter;

/**
 * Servlet implementation class DevolverPrecioServlet
 */
@WebServlet("/DevolverPrecio")
public class DevolverPrecioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverPrecioServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idProducto = request.getParameter("idProducto");
		Integer idUM = Integer.parseInt(request.getParameter("idUM"));
		ProductoAdapter pa = new ProductoAdapter();
		UMProductoAdapter umpa = new UMProductoAdapter();
		PrecioProductoAdapter ppa = new PrecioProductoAdapter();
		JSONObject json = new JSONObject();
		try {
			Producto p = pa.devolverProducto(idProducto);
			UMProducto ump = umpa.devolverUMProducto(idProducto, idUM);
			PrecioProducto pp = ppa.devolverPrecioProducto(p, ump);
			if(pp != null){
				json.put("precio", pp.getPrecio());
			}else{
				json.put("error","error");
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
